package com.rzjm.api.netty.water.business.inhandler;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.rzjm.api.entity.DeviceWater;
import com.rzjm.api.netty.water.NettyUtil;
import com.rzjm.api.netty.water.ResponseData;
import com.rzjm.api.netty.water.constant.ResultCodeEnum;
import com.rzjm.api.netty.water.entity.ReceiveData;
import com.rzjm.api.service.IDeviceWaterMessagesService;
import com.rzjm.api.service.IDeviceWaterService;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Optional;

import static com.rzjm.api.netty.water.constant.SendRtEnum.*;
import static com.rzjm.api.util.DateUtils.localDateTimeStartToSecond;

/**
 *  微信取水
 * @author Mr.Zhou
 * @Description:
 * @date 2025/3/17 9:27
 */
@Component
public class Receive4InHandler implements InHandler {
    private static final Logger LOGGER = LoggerFactory.getLogger(Receive4InHandler.class);
    @Autowired
    private IDeviceWaterService devicesService;
    @Autowired
    private IDeviceWaterMessagesService deviceMessagesService;


    @Override
    public void handler(ChannelHandlerContext ctx, ReceiveData receiveData) {
        //保存Channel
        NettyUtil.addChannel(ctx, receiveData.getId());
        // 保存上报数据日志
        Optional.ofNullable(getMessage(receiveData))
                .ifPresent(message -> deviceMessagesService.save(message));

        //设备应答消息
        Long tag = receiveData.getTag();
        LOGGER.info("接收到的tag: 1111111 " + tag);
        if (tag != null && NettyUtil.SYNC_RESPONSEDATA_MAP.containsKey(tag)) {
            ResponseData responseData = NettyUtil.SYNC_RESPONSEDATA_MAP.get(tag);
            if (responseData != null) {
                LOGGER.info("接收到的tag ===== : " + tag);
                String message = JSONUtil.toJsonStr(receiveData);
                responseData.setCode(ResultCodeEnum.OK.getCode());
                responseData.setMsg(ResultCodeEnum.OK.getDescription());
                responseData.setReceiveDataStr(message);
                responseData.setReceiveData(receiveData);
                responseData.getPromise().setSuccess();
            }else{
                LOGGER.info("tag responseData 取值 为空");
            }
        } else {
            //同步消息或同步非阻塞消息，暂时没有处理逻辑
            LOGGER.info("tag responseData 取值 为空" + tag);
            boolean bl = NettyUtil.SYNC_RESPONSEDATA_MAP.containsKey(tag);
            LOGGER.info("tag responseData 取值 为空: bl  " + bl);
        }

        DeviceWater deviceWater = devicesService.findById(receiveData.getId());
        boolean bl = true;//validateSign(deviceWater, receiveData);
        if(bl){
            //回复消息
            String replyData = requestData(receiveData.getId(), receiveData);
            if (StrUtil.isNotEmpty(replyData)) {
//                reply(replyData, receiveData.getId());
            }
        }else{
            reply("{\"rt\":100,\"type\":3}", receiveData.getId());
        }
    }

    /**
     *
     * @param id
     * @param receiveData
     * @return
     */
    private String requestData(Integer id, ReceiveData receiveData) {
        System.out.println("开始取水数据上报请求：" + JSONUtil.toJsonStr(receiveData));
        DeviceWater device = devicesService.findById(id);
        if (device == null) {
            return "{\"rt\":99,\"v1\":4}";
        }
        String replyData;
        // 当日开始时间的总秒数
        long startSecond = localDateTimeStartToSecond();
        JSONObject obj = JSONUtil.createObj();

        obj = JSONUtil.createObj();
        obj.set("rt", SEND_RT_4.getRt());
        obj.set("v1", 1);
        replyData = JSONUtil.toJsonStr(obj);
        return replyData;
    }
}
